// 此处存放所有的请求链接，用于和后端业务接口对接
const auth = require('./auth_common');
const API_UTILS = {
  //此处封装AJAX，便于统一处理所有请求
  ajax(options, success, fail) {
    let app = getApp();
    let url = options.url || '';
    var _this = this;
    let loginToken = app.globalData.loginToken || wx.getStorageSync("login_token") || "";
    let data = options.data || '',
      method = options.method || 'GET',
      dataType = options.dataType || 'json',
      header = Object.assign({
        'content-type': 'application/json', // application/json & application/x-www-form-urlencoded
        loginToken
      }, options.header);

    wx.request({
      url,
      data,
      header,
      method,
      dataType,
      success: (res) => {
        let data = res.data;
        if (data.code === -8) {
          // 清空所有的授权信息缓存，相当于清除登录态
          wx.removeStorageSync("login_token");
          wx.removeStorageSync("user_info");
          // 重新登录后再次执行 ajax
          auth.initContext(function () {
            _this.ajax(options, success, fail);
          });
          if (fail) {
            fail(res);
          }
        } else {
          success(res);
        }
      },
      fail: () => {
        fail()
      }
    })
  }
}
module.exports = API_UTILS;
